package com.bawei.service.impl;

import com.bawei.mapper.MenuMapper;
import com.bawei.mapper.UserInfoMapper;
import com.bawei.pojo.Menu;
import com.bawei.pojo.MenuExample;
import com.bawei.pojo.UserInfo;
import com.bawei.pojo.UserInfoExample;
import com.bawei.service.UserInfoService;
import com.bawei.util.MD5Utils;
import com.bawei.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public ResultEntity userInfoService(String account, String password) {
        //用户  密码不可以为空
        if (account == null || "".equals(account.trim()) || password == null || "".equals(password.trim())) {
            return new ResultEntity("400", "用户名或者密码不可以为空");
        }
        UserInfo userInfo = this.login(account);
        if (userInfo == null) {
            return new ResultEntity("400", "用户名错误");
        }
        if (userInfo.getPassword().equals(MD5Utils.md5(password))) {
            return new ResultEntity("200", userInfo);
        }
        return new ResultEntity("400", "密码错误");
    }

    @Override
    public List<Menu> menu(String parentId) {
        MenuExample example = new MenuExample();
        MenuExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(String.valueOf(parentId));
        criteria.andParentIdEqualTo(parentId+"");
        List<Menu> menus = menuMapper.selectByExample(example);
        for (Menu m : menus) {
           //二级菜单  递归调用
            List<Menu> menuList = this.menu(m.getId());
            m.setMenuList(menuList);
        }
        return  menus;
    }

    @Override
    public ResultEntity updatePwd(UserInfo userInfo, String oldPassword, String password) {
        if(!userInfo.getPassword().equals(MD5Utils.md5(oldPassword))){
            return new ResultEntity("400", "您的原始密码错误");
        }else{
            userInfo.setPassword(MD5Utils.md5(password));
            int i = userInfoMapper.updateByPrimaryKeySelective(userInfo);
            if(i>0){
                return new ResultEntity("200", "密码修改成功");
            }else{
                return new ResultEntity("400", "系统维修中");
            }
        }
    }


    private UserInfo login(String account) {
        UserInfoExample example = new UserInfoExample();
        UserInfoExample.Criteria criteria = example.createCriteria();
        criteria.andAccountEqualTo(account);
        List<UserInfo> list = userInfoMapper.selectByExample(example);
        if (list.size() == 0 || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
}
